package org.meb.lotrlcg.web;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Session;
import org.hibernate.jdbc.Work;
import org.meb.lotrlcg.model.CardSet;

/**
 * Servlet implementation class TestServlet
 */
@WebServlet("/test")
public class TestServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public TestServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		EntityManagerFactory factory = Persistence
				.createEntityManagerFactory("LOTRLCGUnit");
		EntityManager em = factory.createEntityManager();
		Session session = (Session) em.getDelegate();
		session.doWork(new Work() {

			@Override
			public void execute(Connection c) throws SQLException {
				c.createStatement().execute("set @curr_user_language := 'pl'");
			}
		});
		List<CardSet> list = em.createQuery("from CardSet", CardSet.class)
				.getResultList();
		CardSet cs = list.get(0);
		System.out.println(cs.getCode() + " -> "
				+ cs.getName());
		session.doWork(new Work() {

			@Override
			public void execute(Connection c) throws SQLException {
				c.createStatement().execute("set @curr_user_language := 'en'");
			}
		});
		list = em.createQuery("from CardSet", CardSet.class)
				.getResultList();
		cs = list.get(0);
		em.refresh(cs);
		System.out.println(cs.getCode() + " -> "
				+ cs.getName());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
